package com.lzh.persevere.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.persevere.exception.LzhException;
import com.lzh.persevere.mapper.PhotoMapper;
import com.lzh.persevere.mapper.PhotoTagMapper;
import com.lzh.persevere.model.entity.Photo;
import com.lzh.persevere.model.entity.PhotoTag;
import com.lzh.persevere.model.ro.photo.AddPhotoRO;
import com.lzh.persevere.service.PhotoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 照片表服务实现类
 *
 * @author luzhiheng
 * @since 2025-07-05
 */
@Service
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements PhotoService {

    @Resource
    private PhotoTagMapper photoTagMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addPhoto(AddPhotoRO ro) {
        if (ro.getTagId() == null && StrUtil.isEmpty(ro.getNewTagName())) {
            throw new LzhException(500, "请选择标签或者填写新标签");
        }
        String newTagName = ro.getNewTagName();
        Long tagId = ro.getTagId();
        Photo photo = new Photo()
                .setTagId(tagId)
                .setUrl(ro.getUrl())
                .setPhotoName(ro.getPhotoName())
                .setTakeTime(ro.getTakeTime() == null ? new Date() : ro.getTakeTime());

        if (StrUtil.isNotEmpty(newTagName)) {
            // 新增标签
            PhotoTag photoTag = new PhotoTag();
            photoTagMapper.insert(photoTag.setTagName(newTagName));
            photo.setTagId(photoTag.getId());
        }
        baseMapper.insert(photo);
        return true;
    }
}
